import {View, Text} from "@tarojs/components";
import {
  ActionSheet, ActionSheetItem,
  Button,
  Cell,
  CellGroup,
  Field, Form, Image,
  Radio,
  RadioGroup,
  Space, Stepper,
  Steps
} from "@antmjs/vantui";
import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState} from "react";

import LogUtils from "@/utils/log";
import AssetImage from "@/common/AssetImage";
import Utils from "@/utils/common";
import RouthPath from "@/common/RouthPath";
import {
  AddressModel, CouponsModel,
  KeyTitleModel,
  MachineModel,
  MachineProjectParams,
  ProjectModel,
  TeamModel
} from "@/common/apis/model";
import DateUtils from "@/utils/date_utils";
import StyleUtils from "@/utils/style_utils";
import {
  couponsListPageApi,
  orderSaveApi,
  orderTimeApi,
  teamJoinApi
} from "@/common/apis/home_datasource";
import LocalData from "@/common/local_data";
import NumberUtils from "@/utils/number_utils";
import ShowUtils from "@/utils/show_utils";
import TimeSelect2 from "@/components/time_select";
import EventUtils from "@/utils/event_utils";
import {DynamicFormData} from "@/common/types";
import JsonUtils from "@/utils/json_utils";
import InfoModal from "@/components/InfoModal";
import LocalUtils from "@/utils/local_utils";
import CustomNavBar from "@/components/CustomNavBar";
import MoreOptions2 from "@/pages/project-book/more_options2";
import './index.less'

definePageConfig({
  navigationBarTitleText: '项目预约',
  navigationStyle: 'custom',
})

interface ProjectBookApiParams {
  getType?: any
  getType2?: any
  address?: AddressModel
  address2?: String
  coupons?: CouponsModel
  isRecycling?: any
  beiZhu?: any
  machineId?: MachineModel
  projectId?: ProjectModel
  num2?: number
  scheduleId?: KeyTitleModel
  price?: any
  num?: number
  nickName?: any
  phone?: any
  email?: any
  groupId?: TeamModel,
  moreOptions?: DynamicFormData
}

export default function ProjectBook() {

  const steps = useRef([

    {
      text: '项目信息',
      desc: '',
    },
    {
      text: '客户信息',
      desc: '',
    },
    {
      text: '样品信息',
      desc: '',
    }
  ])
  const childRef = useRef(null); // 仍然使用 useRef

  const [active, setActive] = useState(-1)

  const allData = useRef<ProjectBookApiParams>({});

  //设置值
  const OnSetResult = useCallback((value) => {
    allData.current = {...allData.current, ...value}
    LogUtils.error(allData.current, active)
    if (active < 2) {
      setActive(active + 1)
    } else {
      if (allData.current.getType === '0') {
        if (!Utils.isNotBlank(allData.current.address2)) {
          Utils.showErrorToast('请输入取样地址')
          return
        }
      }
      if (allData.current.isRecycling === '0') {
        if (!allData.current.address) {
          Utils.showErrorToast('请选择回收地址')
          return
        }
      }

      Utils.modal('提示', `确定预约这次检测吗?`, true, (ok) => {
        if (!ok) {
          return;
        }
        const otherIdJsonObj = (!allData.current.moreOptions || Object.keys(allData.current.moreOptions).length === 0)
          ? {}  // 为空时：空对象（不包含 otherIdJson）
          : {otherIdJson: JsonUtils.stringify(Utils.processKeys(allData.current.moreOptions))}; // 非空时：包含该key

        const type = allData.current.machineId?.type
        //转成api需要的参数
        const params = {
          machineId: allData.current.machineId?.id,
          projectId: allData.current.projectId?.id,
          couponsLogId: allData.current.coupons ? allData.current.coupons.id : null,
          //可以不选
          bookAllTimes: allData.current.scheduleId ? DateUtils.formatDateTimeArray(allData.current.scheduleId.key) : '',
          contacts: allData.current.nickName,
          phone: allData.current.phone,
          //可以不选
          teamId: allData.current.groupId ? ShowUtils.getDefault(allData.current.groupId.id, '') : null,
          way: allData.current.getType ? allData.current.getType : '0',
          shootingWay: allData.current.getType2 ? allData.current.getType2 : '0',
          //可以不选
          recycleDetail: allData.current.address ? ShowUtils.getDefault(allData.current.address.address, '') : '',
          wayDetail: allData.current.address2,
          note: allData.current.beiZhu,
          recycle: allData.current.isRecycling ? allData.current.isRecycling : '1',
          amount: allData.current.price,
          actualAmount: allData.current.price,
          email: allData.current.email,
          bookTotalTime: type === LocalData.notTimeId ? allData.current.num ?? 1 : allData.current.scheduleId ? allData.current.scheduleId.key.length / 2 : '',
          ...(allData.current.projectId?.appendixOneName && {
            appendixOneName: allData.current.projectId.appendixOneName,
            appendixOnePrice: allData.current.projectId.appendixOnePrice,
            appendixOneNum: allData.current.num2,
          }),
          ...otherIdJsonObj
        }
        orderSaveApi(params).then((res) => {
          if (res) {
            setTimeout(() => {
              Utils.showToastAndNavigate(
                '预约成功！', // title
                2,           // delta
                1000,        // delay
                () => {      // callback function
                  // 这里是你希望在导航前执行的、特定于此页面的代码
                  EventUtils.trigger(EventUtils.RefreshOrder, true);
                  EventUtils.trigger(EventUtils.UserInfo, true);
                }
              );
            }, 100);
          }
        })
      })
    }
  }, [active]);

  useEffect(() => {
    const params = Utils.getParamsByRouter(Utils.getI())
    const {mobile, realName} = LocalUtils.getMobileOrRealName()
    if (params && params.data) {
      const p = Utils.getObjectWithUrl<MachineProjectParams>(params.data)
      allData.current = {
        getType: '0',
        projectId: p.projectId,
        machineId: p.machineId,
        num: 0,
        num2: 0,
        phone: mobile,
        nickName: realName,
        //由于是按照个数算价格，就默认了价格，num虽然设置了0，但是Stepper会默认成1
        price: p.machineId.type === LocalData.notTimeId ? p.projectId.price : undefined
      }
    }
    LogUtils.info(allData.current)
    setActive(0)
    showModal()
  }, []);

  const [modalVisible, setModalVisible] = useState(false)

  const handleClose = () => {
    setModalVisible(false);
  };

  const showModal = () => {
    if (Utils.isNotBlank(getNeeds())) {
      setModalVisible(true);
    }
  };

  const getNeeds = useCallback(() => {
    return allData.current.projectId?.needs
  }, []);

  return (
    <View style={{
      display: 'flex',
      flexDirection: 'column',
      height: '100VH',
      boxSizing: 'border-box'
    }}
    >
      <View style={{
        zIndex: 0,
      }}
      >
        <CustomNavBar
          title='项目预约'
          showLeftIcon
        >
          <View style={{"--cell-background-color": "transparent"}}>
            <Cell
              border={false}
              renderLabel={<Text style={{color: 'red'}}>{ShowUtils.getShowNote(allData.current.projectId?.note)}</Text>}
              renderTitle={<Text
                style={{marginRight: '20px', color: 'black', fontWeight: "bold", fontSize: '18px'}}
              >
                {`${ShowUtils.getDefault(allData.current.machineId?.name)}/${ShowUtils.getDefault(allData.current.projectId?.name)}`}
              </Text>}
              renderRightIcon={<Text onClick={() => {
                showModal()
              }}
              >预约须知</Text>}
            />
          </View>
        </CustomNavBar>
        <Steps steps={steps.current} active={active} activeIcon='success' activeColor='#38f'
               style={{margin: '0 20px'}}
        /></View>
      <View style={{flex: 1, overflowY: 'auto', boxSizing: 'border-box', paddingBottom: '80px'}}>
        {active === 0 ? <ProjectInfo ref={childRef} OnSetResult={OnSetResult} initialData={allData.current}/> : null}
        {active === 1 ? <UserInfo ref={childRef} OnSetResult={OnSetResult} initialData={allData.current}/> : null}
        {active === 2 ? <SampleInfo ref={childRef} OnSetResult={OnSetResult} initialData={allData.current}/> : null}
      </View>
      <FooterButton disabled={active === 0} handleSubmit={() => {
        if (childRef.current) {
          childRef.current.handleSubmit()
        }
      }} onChangeActive={() => {
        if (active > 0) {
          setActive(active - 1)
        }
      }}
      />
      <InfoModal
        show={modalVisible}
        title='预约须知'
        onClose={() => handleClose()}
        onConfirm={() => handleClose()}
      >
        <View>
          <Text>
            {getNeeds()}
          </Text>
        </View>
      </InfoModal>
    </View>
  )
}

interface UserInfoProps {
  OnSetResult: (value: any) => void;
  initialData: Record<string, any>; // Receive initial data
}

interface UserInfoModel {
  nickName?: any
  phone?: any
  email?: any
  groupId?: TeamModel
}


const UserInfo = forwardRef<any, UserInfoProps>(({OnSetResult, initialData}, ref) => {

  const [fieldValues, setFieldValues] = useState<UserInfoModel>({})

  const handleSubmit = () => {
    LogUtils.info(fieldValues)
    if (fieldValues) {
      if (!Utils.isNotBlank(fieldValues.nickName)) {
        Utils.showErrorToast('客户姓名不能为空')
        return;
      }
      if (!Utils.isMobilePhone(fieldValues.phone)) {
        Utils.showErrorToast('客户电话格式不对')
        return;
      }
      if (Utils.isNotBlank(fieldValues.email) && !Utils.isEmail(fieldValues.email)) {
        Utils.showErrorToast('邮箱格式不对')
        return;
      }
    }
    OnSetResult(fieldValues); // Use the prop function name
  };

  useImperativeHandle(ref, () => ({
    handleSubmit: handleSubmit
  }));
  useEffect(() => {
    setFieldValues({
      nickName: initialData.nickName,
      phone: initialData.phone,
      email: initialData.email,
      groupId: initialData.groupId,
    })
  }, [initialData]);

  const handleGroupSelect = (e: any) => {
    setFieldValues(prev => ({
      ...prev,
      groupId: e.detail
    }));
    setShow(false)
  }

  const inputChange = useCallback((e, type) => {
    //修改值
    setFieldValues((prevValues) => {
      const newValues = {...prevValues};
      if (type === "0") {
        newValues.nickName = e;
      } else if (type === "1") {
        newValues.phone = e;
      } else if (type === "2") {
        newValues.email = e;
      }
      return newValues;
    });

  }, []);
  const [show, setShow] = useState(false)

  const [, setRefresh] = useState({})

  const actions = useRef<ActionSheetItem[]>()
  useEffect(() => {
    teamJoinApi(true).then((res) => {
      if (res) {
        actions.current = res;
        setRefresh({})
      }
    })
  }, []);
  const styleBg = useRef(StyleUtils.getStyleBg());
  return (
    <View style={{width: '100%', display: 'flex', flexDirection: 'column', '--cell-group-title-color': 'black'}}>
      <CellGroup title='客户信息'>
        <Cell title='客户姓名' required/>
        <View style={{padding: '0 20px 20px 10px', boxSizing: 'border-box'}}>
          <Field
            style={styleBg.current}
            value={fieldValues ? fieldValues.nickName : ''}
            placeholder='请输入客户姓名'
            onInput={(e) => inputChange(e.detail, "0")}
            border={false}
          />
        </View>
        <Cell title='客户电话' required/>
        <View style={{padding: '0 20px 20px 10px', boxSizing: 'border-box'}}>
          <Field
            style={styleBg.current}
            value={fieldValues ? fieldValues.phone : ''}
            placeholder='请输入客户电话'
            type='number'
            onInput={(e) => inputChange(e.detail, "1")}
            border={false}
          />
        </View>
        <Cell title='客户邮箱'/>
        <View style={{padding: '0 20px 20px 10px', boxSizing: 'border-box'}}>
          <Field
            style={styleBg.current}
            value={fieldValues ? fieldValues.email : ''}
            placeholder='请输入邮箱，方便给您发送测试结果'
            type='text'
            onInput={(e) => inputChange(e.detail, "2")}
            border={false}
          />
        </View>
        {
          !Utils.isEmpty(actions.current) ? <Cell
            renderIcon={<Text style={{marginRight: '20px'}}>请选择团队</Text>}
            renderTitle={<Text
              style={StyleUtils.getMaxLines(2, {
                paddingLeft: '20px',
                color: !fieldValues.groupId ? AssetImage.gray2 : 'black',
                textAlign: 'right'
              })}
            >{fieldValues.groupId ? fieldValues.groupId.name : '请选择'}</Text>}
            onClick={() => {
              setShow(true)
            }}
            isLink
          /> : null
        }
      </CellGroup>
      <ActionSheet
        show={show}
        actions={actions.current}
        onClose={() => setShow(false)}
        onSelect={(e) => handleGroupSelect(e)}
      />
    </View>
  );
});

interface SampleInfoProps {
  OnSetResult: (value: any) => void;
  initialData: Record<string, any>; // Receive initial data
}

interface SampleInfoModel {
  getType?: any
  getType2?: any
  address?: AddressModel
  address2?: String
  isRecycling?: any
  beiZhu?: any
}

const SampleInfo = forwardRef<any, SampleInfoProps>(({OnSetResult, initialData}, ref) => {
  // The 'ref' argument is ignored here!


  const [fieldValues, setFieldValues] = useState<SampleInfoModel>({})


  const options = useRef(LocalData.way);
  const options3 = useRef(LocalData.way2);

  const options2 = useRef(LocalData.recycle);
  useEffect(() => {
    setFieldValues({
      getType: initialData.getType,
      getType2: initialData.getType2,
      isRecycling: initialData.isRecycling,
      address: initialData.address,
      address2: initialData.address2,
      beiZhu: initialData.beiZhu
    })
  }, [initialData]);
  const handleSubmit = () => {
    OnSetResult(fieldValues); //
  };

  useImperativeHandle(ref, () => ({
    handleSubmit: handleSubmit
  }));

  const radioChange = useCallback((e, type) => {
    //修改值
    setFieldValues((prevValues) => {
      LogUtils.info(e)
      const newValues = {...prevValues};
      if (type === "0") {
        newValues.getType = e.detail;
      } else if (type === "4") {
        newValues.getType2 = e.detail;
      } else if (type === "1") {
        newValues.isRecycling = e.detail;
      } else if (type === "3") {
        newValues.address = e;
      } else if (type === "5") {
        newValues.address2 = e;
      } else {
        newValues.beiZhu = e;
      }
      return newValues;
    });

  }, []);


  const goAddress = useCallback(() => {
    const url = Utils.getUrlWithObject(RouthPath.addressList, {isOk: true});

    Utils.navigateAndListenToEvent(url, 'selectAddress', (data) => {
      if (data) {
        radioChange(data, "3")
      }
    })
  }, []);
  const styleBg = useRef(StyleUtils.getStyleBg());

  const renderQyStyle = useCallback(() => {
    if (fieldValues.getType === "2") {
      return null
    } else if (fieldValues.getType === "1") {
      return (<Cell required
                    renderTitle={<Text
                      style={{
                        display: 'inline-block',
                        marginLeft: '20px',
                        fontSize: '14px',
                      }}
                    >{LocalData.acceptAddress}</Text>}
                    renderExtra={<Image src={AssetImage.copy}
                                        style={{width: '24px', height: '24px'}}
                    />}
                    renderIcon={<Text>邮寄地址</Text>}
                    onClick={() => {
                      Utils.copyToClipboard()
                    }}
      />)
    } else {
      return (<Cell required
                    renderTitle={<Field
                      style={styleBg.current}
                      value={fieldValues.address2 ? fieldValues.address2 : ''}
                      placeholder='请输入取样地址'
                      type='text'
                      onInput={(e) => radioChange(e.detail, "5")}
                      border={false}
                    />}
                    renderIcon={<Text style={{marginRight: '20px'}}>取样地址</Text>}
      />)
    }
  }, [fieldValues.address, fieldValues.getType, radioChange]);


  return (
    <View style={{width: '100%', display: 'flex', flexDirection: 'column', '--cell-group-title-color': 'black'}}>
      <CellGroup title='样品信息'>
        <Cell required renderTitle={<View style={{marginLeft: '20px'}}><RadioGroup
          value={fieldValues.getType2 ? fieldValues.getType2 : options3.current[0].value}
          onChange={(e) => radioChange(e, "4")}
          direction='horizontal'
          style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
        >   {options3.current.map((option) => (
          <Radio
            key={option.value}
            name={String(option.value)}
            shape='square'
          >
            {option.label}
          </Radio>
        ))}
        </RadioGroup></View>} renderIcon={<Text>拍摄方式</Text>}
        />
        <Cell required renderTitle={<View style={{marginLeft: '20px'}}><RadioGroup
          value={fieldValues.getType ? fieldValues.getType : options.current[0].value}
          onChange={(e) => radioChange(e, "0")}
          direction='horizontal'
          style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
        >   {options.current.map((option) => (
          <Radio
            key={option.value}
            name={String(option.value)}
            shape='square'
          >
            {option.label}
          </Radio>
        ))}
        </RadioGroup></View>} renderIcon={<Text>取样方式</Text>}
        />
        {
          renderQyStyle()
        }
        <Cell required renderTitle={<View style={{marginLeft: '20px'}}><RadioGroup
          value={fieldValues.isRecycling ? fieldValues.isRecycling : options2.current[1].value}
          onChange={(e) => radioChange(e, "1")}
          direction='horizontal'
          style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
        >   {options2.current.map((option) => (
          <Radio
            key={option.value}
            name={String(option.value)}
            shape='square'
          >
            {option.label}
          </Radio>
        ))}
        </RadioGroup></View>} renderIcon={<Text>是否回收</Text>}
        />
        {
          fieldValues.isRecycling === "0" ? <Cell required
                                                  renderTitle={<Text
                                                    style={{
                                                      marginLeft: '20px',
                                                      color: fieldValues.address ? 'black' : AssetImage.gray2
                                                    }}
                                                  >{fieldValues.address ? fieldValues.address.address : '请选择'}</Text>}
                                                  renderIcon={<Text>选择地址</Text>} isLink
                                                  onClick={() => {
                                                    goAddress();
                                                  }}
          /> : null

        }
        <CellGroup title='备注信息' border={false}>
          <View style={{padding: '0 20px'}}>
            <Field
              style={styleBg.current}
              value={fieldValues.beiZhu}
              type='textarea'
              placeholder='请输入备注信息'
              autosize={{minHeight: '150px', maxHeight: '150px'}}
              onChange={(e) => radioChange(e.detail, "2")}
              border={false}
            />
          </View>
        </CellGroup>
      </CellGroup>
    </View>
  )
});


interface ProjectInfoModel {
  machineId?: MachineModel
  projectId?: ProjectModel
  coupons?: CouponsModel
  scheduleId?: KeyTitleModel
  price: any
  num?: number
  num2?: number
  moreOptions?: DynamicFormData
}


interface ProjectInfoProps {
  OnSetResult: (value: Partial<ProjectInfoModel>) => void;
  initialData: Partial<ProjectInfoModel>; // Receive initial data
}

const ProjectInfo = forwardRef<any, ProjectInfoProps>(({OnSetResult, initialData}, ref) => {


  const [result, setResult] = useState<ProjectInfoModel>(() => {
    return {
      machineId: initialData.machineId || undefined,
      projectId: initialData.projectId || undefined,
      coupons: initialData.coupons || undefined,
      scheduleId: initialData.scheduleId || undefined,
      moreOptions: initialData.moreOptions || undefined,
      num: initialData.num || undefined,
      num2: initialData.num2 || undefined,
      price: initialData.price || undefined,
    };
  });

  const handleSubmit = () => {
    if (result.machineId?.type === LocalData.notTimeId || result.scheduleId) {
      form.validateFields((errors, values) => {
        if (!errors || errors.length === 0) {
          result.moreOptions = values;
          OnSetResult(result);
        }
      });
    } else {
      Utils.showErrorToast('请完善项目信息');
    }
  };
  useImperativeHandle(ref, () => ({
    handleSubmit: handleSubmit
  }));
  const [showCoupons, setShowCoupons] = useState(false)
  //机器列表
  const coupons = useRef<CouponsModel[]>([])
  const [showCouponsCell, setShowCouponsCell] = useState(false)
  const getCouponsList = useCallback(() => {
    couponsListPageApi(0, true).then(res => {
      if (res) {
        coupons.current = res
        setShowCouponsCell(res.length > 0)
        if (initialData.price) {
          initCoupons(initialData.price)
        }
      }
    })
  }, []);

  const initCoupons = useCallback((price: number) => {
    if (price && price > 0) {
      coupons.current = coupons.current.map(item => {
        item.name = item.title;
        item.value = item.id;
        item.disabled = (item.type === 1 && price < NumberUtils.stringToNumber(item.minAmount));
        return item;
      });
    }
  }, []);


  //判断是否清空
  const [availability, setAvailability] = useState<string>()
  const getProjectTimes = useCallback((id) => {
    orderTimeApi(id).then((data) => {
      if (data) {
        LogUtils.info(data)
        setAvailability(data.length > 0 ? data.join(",") : '')
      }
    })
  }, []);

  const handleCouponsSelect = (e: any) => {
    const selectedCoupon = e.detail;

    if (result.coupons?.id === selectedCoupon.id) {
      return;
    }
    const discount = selectedCoupon.discount || 0;
    setResult(prev => {
      const newActualAmount = prev.price - discount;
      return {
        ...prev,
        coupons: selectedCoupon,
        price: Math.max(0, newActualAmount),
      };
    });
    setShowCoupons(false)
  }
  const handleBeforeTimeSelectOpen = useCallback(() => {
    if (!result.machineId) {
      Utils.showErrorToast('请先选择机器');
      return false; // Prevent opening
    }
    if (!result.projectId) {
      Utils.showErrorToast('请先选择项目');
      return false; // Prevent opening
    }
    // Add any other conditions if needed
    return true; // All
  }, [result.machineId, result.projectId]);


  const calculateItemPrice = useCallback((quantity: number, unitPrice: string | number) => {
    return quantity * NumberUtils.stringToFloat(unitPrice || '0');
  }, []);


  const handleNumChange = useCallback((e) => {
    const newNum = e.detail;
    setResult(prev => {
      if (!prev.projectId) {
        return prev;
      }

      // 1. 计算项目1的新价格
      const price1 = calculateItemPrice(newNum, prev.projectId.price);

      // 2. 如果存在项目2，计算项目2的价格
      const price2 = prev.projectId.appendixOnePrice
        ? calculateItemPrice(prev.num2 || 0, prev.projectId.appendixOnePrice)
        : 0;

      // 3. 计算最终总价
      const totalPrice = price1 + price2;

      // 4. 使用最终总价，统一处理副作用
      initCoupons(totalPrice);

      // 5. 返回新状态
      return {
        ...prev,
        num: newNum,
        price: totalPrice.toFixed(2),
        coupons: undefined,
      };
    });
  }, [calculateItemPrice, initCoupons]);

  const handleNumChange2 = useCallback((e) => {
    const newNum2 = e.detail;
    setResult(prev => {
      // 防御性编程：如果 projectId 或 projectId2 不存在，则不进行任何操作
      if (!prev.projectId || !prev.projectId.appendixOnePrice) {
        return prev;
      }
      LogUtils.info(prev.num)
      // 1. 计算项目1的价格 (逻辑不变)
      const price1 = prev.scheduleId
        ? calculateItemPrice(prev.scheduleId.key.length / 2, prev.projectId.price)
        : calculateItemPrice(prev.num || 0, prev.projectId.price);
      // 2. 计算项目2的价格
      const price2 = calculateItemPrice(newNum2, prev.projectId.appendixOnePrice);
      // 3. 计算最终总价
      const totalPrice = price1 + price2;

      // 4. 使用最终总价，统一处理副作用
      initCoupons(totalPrice);

      // 5. 返回新状态
      return {
        ...prev,
        num2: newNum2,
        price: totalPrice.toFixed(2),
        coupons: undefined,
      };
    });
  }, [calculateItemPrice, initCoupons]);

  const selectTimes = useCallback((ids: any) => {
    if (ids.length === 0) {
      return;
    }
    const hours = ids.length / 2;
    const showTimes = DateUtils.convertSlotIdToDescription(ids[0]);
    setResult(prev => {
      if (!prev.projectId) {
        return prev;
      }
      // 1. 根据时长计算项目1的价格
      const price1 = calculateItemPrice(hours, prev.projectId.price);

      // 2. 如果存在项目2，计算项目2的价格
      const price2 = prev.projectId.appendixOnePrice
        ? calculateItemPrice(prev.num2 || 0, prev.projectId.appendixOnePrice)
        : 0;
      // 3. 计算最终总价
      const totalPrice = price1 + price2;

      // 4. 使用最终总价，统一处理副作用
      initCoupons(totalPrice);
      return {
        ...prev,
        scheduleId: {
          key: ids,
          title: `${showTimes} 共${hours}小时`
        },
        price: totalPrice.toFixed(2),
        coupons: undefined,
      };
    });
  }, [calculateItemPrice, initCoupons]); // Dependencies might be needed if logic uses external vars

  useEffect(() => {
    if (result.machineId) {
      if (result.machineId.type !== LocalData.notTimeId) {
        getProjectTimes(result.machineId.id)
      }
    }
    getCouponsList()
  }, []);

  const renderTimeOrStep = useCallback((type) => {
    if (type == 0) {
      return (
        <Cell renderIcon={<Text>样品数量</Text>}
              renderTitle={<View style={{
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                '--stepper-input-disabled-text-color': 'black',
              }}
              ><Stepper
                value={result.num} integer disableInput onChange={(e) => {
                handleNumChange(e)
              }} disabled={!(result.machineId && result.projectId)}
              /></View>}
        />)
    } else {
      return (<TimeSelect2
          onBeforeOpen={handleBeforeTimeSelectOpen}
          items={DateUtils.getSelectTimes(availability ?? '')} max={10}
          onComplete={(values2) => {
            selectTimes(values2);
          }}
          initValues={result.scheduleId?.key ?? []}
          renderTitle={<Text
            style={StyleUtils.getMaxLines(2, {
              paddingLeft: '20px',
              color: !result.scheduleId ? AssetImage.gray2 : 'black',
              textAlign: 'right'
            })}
          >{result.scheduleId ? result.scheduleId.title : '请选择'}</Text>}
        />
      )
    }
  }, [availability, handleNumChange, result.machineId, result.num, result.projectId, result.scheduleId, selectTimes]);


  const renderCoupons = useCallback(() => {
    return (
      showCouponsCell ? <Cell
        renderIcon={<Text style={{marginRight: '20px'}}>请选择优惠券</Text>}
        renderTitle={<View style={{display: 'flex', flexDirection: 'row', justifyContent: 'flex-end'}}>
          <Text
            style={StyleUtils.getMaxLines(2, {
              paddingLeft: '20px',
              color: !result.coupons ? AssetImage.gray2 : 'red',
              textAlign: 'right'
            })}
          >{result.coupons ? `-${ShowUtils.getDefaultPrice(result.coupons.discount)}` : '请选择'}</Text>
        </View>}
        onClick={() => {
          if (!result.price) {
            Utils.showErrorToast('请先确认价格');
            return;
          }
          setShowCoupons(true)
        }}
        isLink
      /> : null
    )
  }, [result.coupons, result.price, showCouponsCell]);


  const render2Project = useCallback(() => {
    return result.projectId?.appendixOnePrice ? (
      <Cell renderIcon={<Text>{result.projectId?.appendixOneName}</Text>}
            renderTitle={<View style={{
              display: 'flex',
              flexDirection: 'row',
              justifyContent: 'flex-end',
              alignItems: 'center',
              '--stepper-input-disabled-text-color': 'black',
            }}
            ><Stepper
              min={0}
              value={result.num2} integer onChange={(e) => {
              handleNumChange2(e)
            }} disabled={!(result.machineId && result.projectId.appendixOnePrice)}
            /><Text style={{
              color: 'red',
              paddingLeft: '5px'
            }}
            >{ShowUtils.getDefaultPrice(result.projectId.appendixOnePrice)}</Text></View>}
      />
    ) : null
  }, [result.machineId, result.projectId?.appendixOnePrice]);
  const form = Form.useForm();

  return (
    <View>
      <CellGroup title={<Text style={{color: 'black'}}>项目信息</Text>}>
        {
          renderTimeOrStep(result.machineId?.type)
        }
        {
          render2Project()
        }
        {/* Use state value for display and color check */}
        <Cell title='价格'>
          <Text
            style={{color: Utils.isThanZero(result.price) ? 'red' : AssetImage.gray2}}
          >{ShowUtils.getDefaultPrice(result.price ? result.price : '0')}</Text>
        </Cell>
        {
          renderCoupons()
        }
      </CellGroup>
      <MoreOptions2 id={result.projectId?.id} moreOptions={result.moreOptions} form={form} />
      <ActionSheet
        show={showCoupons}
        actions={coupons.current}
        onClose={() => setShowCoupons(false)}
        onSelect={(e) => handleCouponsSelect(e)}
      />
    </View>
  )
});


function FooterButton(props) {
  return <View className='fixed-footer'>
    <Space>
      <Button type='info' disabled={props.disabled} plain hairline onClick={() => {
        if (props.onChangeActive) {
          props.onChangeActive()
        }
      }}
      >
        上一步
      </Button>
      <Button
        type='info' onClick={() => {
        props.handleSubmit()
      }}
      >
        下一步
      </Button>
    </Space>
  </View>
}
